package SGEngine2

import (
	"github.com/gl"
	"strings"
)

const (
	Pivot_CENTER = iota
	Pivot_BOTTOMLEFT
	Pivot_TOPLEFT
	Pivot_TOP
	Pivot_TOPRIGHT
	Pivot_LEFT
	Pivot_RIGHT
	Pivot_BOTTOM

	Pivot_BOTTOM_RIGHT
)

type Component2D struct {
	BaseComponent
	Node   *Node
	Pivot  int
	Width  float32
	Height float32
}

func (this *Component2D) GetPivotOffset() Vec2 {
	var v Vec2
	if this.Pivot == Pivot_TOP || this.Pivot == Pivot_CENTER || this.Pivot == Pivot_BOTTOM {
		v.X = 0.5
	} else if this.Pivot == Pivot_RIGHT || this.Pivot == Pivot_TOPRIGHT || this.Pivot == Pivot_BOTTOM_RIGHT {
		v.X = 1
	} else {
		v.X = 0
	}

	if this.Pivot == Pivot_LEFT || this.Pivot == Pivot_CENTER || this.Pivot == Pivot_RIGHT {
		v.Y = 0.5
	} else if this.Pivot == Pivot_TOPLEFT || this.Pivot == Pivot_TOP || this.Pivot == Pivot_TOPRIGHT {
		v.Y = 1
	} else {
		v.Y = 0
	}
	return v
}
func (this *Component2D) OnAttach(node *Node) {
	this.Node = node
	render := new(Renderer)
	this.Node.render = render
}

func (this *Component2D) GenTextureMaterial(texName string) *Material {
	mat := new(Material)
	mat.Shader = ShaderManager.SahderGet("Texture")
	mat.Tex = LoadImage(texName)
	strExt := strings.Split(texName, ".")[1]
	if strExt == "png" {
		mat.IsTrans = true
	} else {
		mat.IsTrans = false
	}
	return mat
}
func (this *Component2D) GenQuadVerticeMesh() (*Bounds, []float32) {
	b := new(Bounds)
	pv := this.GetPivotOffset()
	// X = left, Y = bottom, Z = right, W = top
	var v4 Vec4
	v4.X = 0 - pv.X
	v4.Y = 0 - pv.Y
	v4.Z = 1 - pv.X
	v4.W = 1 - pv.Y
	v4.X *= float64(this.Width)
	v4.Y *= float64(this.Height)
	v4.Z *= float64(this.Width)
	v4.W *= float64(this.Height)

	b.Min = Vec3{v4.X, v4.Y, 0}
	b.Max = Vec3{v4.Z, v4.W, 0}
	b.Center = Vec3{0, 0, 0}

	Vertices := []float32{
		float32(v4.X), float32(v4.Y), 0.0,
		float32(v4.Z), float32(v4.Y), 0.0,
		float32(v4.X), float32(v4.W), 0.0,
		float32(v4.Z), float32(v4.W), 0.0,
	}
	return b, Vertices
}

func (this *Component2D) GenQuadMesh(color *Color4, isUV bool) *Mesh {
	mesh := new(Mesh)
	this.Node.Bounds, mesh.Vertices = this.GenQuadVerticeMesh()
	mesh.Vertbuffer = gl.GenBuffer()
	mesh.Vertbuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, 12*4, mesh.Vertices, gl.STATIC_DRAW)

	if isUV {
		mesh.UV = []float32{
			0, 0,
			1, 0,
			0, 1,
			1, 1,
		}
		mesh.UVbuffer = gl.GenBuffer()
		mesh.UVbuffer.Bind(gl.ARRAY_BUFFER)
		gl.BufferData(gl.ARRAY_BUFFER, 8*4, mesh.UV, gl.STATIC_DRAW)
	}

	if color != nil {
		mesh.Color = []float32{
			color.R, color.G, color.B, color.A,
			color.R, color.G, color.B, color.A,
			color.R, color.G, color.B, color.A,
			color.R, color.G, color.B, color.A,
		}
		mesh.Colorbuffer = gl.GenBuffer()
		mesh.Colorbuffer.Bind(gl.ARRAY_BUFFER)
		gl.BufferData(gl.ARRAY_BUFFER, 16*4, mesh.Color, gl.STATIC_DRAW)
	}
	return mesh
}

func (this *Component2D) SetSize(width float32, height float32) {
	this.Width = width
	this.Height = height
}
